package com.surfin.safe.keyboard;

import android.text.TextUtils;
import android.util.ArrayMap;

public class KeyboardManager {

    private KeyboardManager() {
    }

    private static KeyboardManager INSTANCE;

    public static KeyboardManager getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new KeyboardManager();
        }
        return INSTANCE;
    }

    // 保存EditText和对应的数据
    private final static ArrayMap<String, byte[]> mDataMap = new ArrayMap<>();

    /**
     * 保存指定EditText输入的内容
     */
    public void addKey(String editTextId) {
        String data = JNIMethod.getKey(String.valueOf(editTextId));
        if (TextUtils.isEmpty(data)) {
            return;
        }
        mDataMap.put(editTextId, JNIMethod.encryption(data.getBytes()));
    }

    /**
     * 删除指定EditText内容，页面销毁的时候调用
     */
    public void releaseKey(String editTextId) {
        mDataMap.remove(editTextId);
    }

    /**
     * 清空指定EditText内容
     */
    public void clearKey(String editTextId) {
        mDataMap.put(editTextId, "".getBytes());
    }

    /**
     * 删除内容
     */
    public void deleteKey(String editTextId) {
        mDataMap.remove(editTextId);
        // 删除数据后获取最新的数据
        addKey(editTextId);
    }

    /**
     * 根据editTextId获取对应的数据
     */
    public String getEditString(String editTextId) {
        if (TextUtils.isEmpty(editTextId) || mDataMap.isEmpty()) {
            return "";
        }
        byte[] bytes = mDataMap.get(editTextId);
        if (bytes == null) {
            return "";
        }
        byte[] crypt = JNIMethod.cryption(bytes);
        if (crypt == null) {
            return "";
        }
        return new String(crypt);
    }
}
